<template>
    <div class="bg-gray-100 flex-1">
        <!-- 右侧内容区域 -->
        <div class="flex-1 p-4">
            <!-- 标题和搜索框 -->
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-3xl font-semibold">病人管理</h2>
            </div>
            <!-- 历史记录表格 -->
            <div class="bg-white p-2 rounded-lg shadow-md mx-auto">
                <var-tabs indicator-color="#006263" active-color="#006263" v-model:active="activeTab">
                    <var-tab>有效</var-tab>
                    <var-tab>已禁用</var-tab>
                </var-tabs>
                <div class="max-h-[528px] overflow-y-auto relative">
                <table class="min-w-full">
                    <thead>
                        <tr>
                            <th v-for="header in headers" :key="header" class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">
                                {{ header }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="listLoading">
                            <td colspan="9" class="px-6 py-1.4 text-center text-base text-gray-500">
                                <var-loading description="LOADING" color="#006263" />
                            </td>
                        </tr>
                        <tr v-if="list.length === 0 && !listLoading">
                            <td colspan="9" class="px-6 py-1.4 text-center text-base text-gray-500">暂无数据</td>
                        </tr>
                        <tr v-for="(record, index) in list" :key="index" class="odd:bg-white even:bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                            <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ record.name || '-' }}</td>
                            <td class="px-6 py-1.5 text-center text-base text-gray-500">{{ record.sex || '-' }}</td>
                            <td class="px-6 py-1.5 text-center text-base text-gray-500">{{ record.age || '-' }}</td>
                            <td class="px-6 py-1.5 text-center text-base text-gray-500">{{ record.departmentName || '-' }}</td>
                            <td class="px-6 py-1.5 text-center text-base text-gray-500">{{ record.creatorName || '-' }}</td>
                            <td class="px-6 py-1.5 text-center text-base text-gray-500">{{ formatDate(record.createdAt) || '-' }}</td>
                            <td class="px-6 py-1.5 text-base">
                                    <div class="flex flex-col items-center justify-center">
                                        <var-space :size="[10, 10]">
                                            <var-button block color="#006263" text-color="white" @click="getRecord(record.patientId)" style="border-radius: 8px">查看</var-button>
                                        </var-space>
                                    </div>
                                </td>
                            <td class="px-6 py-1.5 text-base text-blue-500 hover:text-blue-800 flex justify-center items-center">
                                <var-space :size="[10, 10]">
                                    <var-button block color="#006263" text-color="white" @click="viewRecord(record)" class="w-35" style="border-radius: 8px">编 辑</var-button>
                                </var-space>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
                <!-- 分页组件 -->
                <div class="flex justify-center mt-6">
                    <var-pagination v-model="currentPage" v-model:size="pageSize" :total="total" :size-option="[10, 20, 30]" :simple="true" @change="handlePageChange" style="color: #006263" />
                </div>
            </div>
        </div>
        <!--删除病人信息确认弹窗-->
        <var-dialog v-model:show="showConfirm" title="删除提示" confirm-button-text-color="red" persistent cancel-button-text-color="#006263" width="35vw" @before-close="deletePatient">
            <var-loading description="LOADING" color="red" :loading="deleteLoading">
                <div class="p-4">
                    <p class="text-lg text-gray-900">确认删除此用户？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <!--恢复病人信息弹窗-->
        <var-dialog v-model:show="showRecoverConfirm" title="恢复提示" comfirm-button-text-color="green" persistent cancel-button-text-color="#006263" wid="35vw" @before-close="recoverPatient">
            <var-loading description="LOADING" color="green" :loading="recoverLoading">
                <div class="p-4">
                    <p class="text-lg text-gray-900">确认恢复此用户？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <var-popup v-model:show="showRecordPopup" class="w-[25vw] h-[42vh] rounded-lg p-2">
            <div class=" max-h-[288px] flex justify-center items-center overflow-auto relative">
                <table class="min-w-full">
                    <thead>
                        <tr>
                            <th class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">就诊记录</th>
                            <th class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">查看</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="recordList.length === 0">
                            <td colspan="2" class="px-6 py-1.4 text-center text-base text-gray-500">暂无数据</td>
                        </tr>
                        <tr v-for="(record, index) in recordList" :key="index" class="odd:bg-white even:bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                            <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ format(record.createdAt) }}</td>
                            <td class="px-6 py-1.5 text-base">
                                <div class="flex flex-col items-center justify-center">
                                    <var-space :size="[10, 10]">
                                        <var-button block color="#006263" text-color="white" @click="getRecordDetails(record.recordId)" style="border-radius: 8px">查看</var-button>
                                    </var-space>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </var-popup>
        <!-- 居中弹窗 -->
        <var-popup v-model:show="showCenterPopup">
            <var-loading description="LOADING" color="#006263" :loading="loading">
                <div class="p-9 w-[500px] h-[690px] bg-white rounded-lg shadow-lg">
                    <!-- 弹窗内容 -->
                    <h3 class="text-lg font-semibold mb-2">{{ updatePatient.name }}的个人信息</h3>
                    <div class="grid grid-cols-5 mb-8">
                        <!--左边列-->
                    </div>
                    <!--姓名-->
                    <div class="mb-14">
                        <var-input label="姓名" :rules="nameRules" focus-color="#006263" v-model="updatePatient.name" placeholder="请输入修改后的姓名" variant="outlined" />
                    </div>
                    <!--性别-->
                    <div class="mb-14">
                        <var-select label="性别" v-model="updatePatient.sex" placeholder="请选择性别" focus-color="#006263" variant="outlined">
                            <var-option v-for="option in sexOptions" :key="option.value" :label="option.label" :value="option.value" />
                        </var-select>
                    </div>
                    <!--联系方式-->
                    <div class="mb-14">
                        <var-input label="联系方式" :rules="phoneRules" v-model="updatePatient.phone" focus-color="#006263" placeholder="请输入电话号码" variant="outlined" />
                    </div>
                    <!--右边-->
                    <div>
                        <!-- 年龄 -->
                        <div class="mb-14">
                            <var-input label="年龄" :rules="ageRules" v-model="updatePatient.age" type="number" focus-color="#006263" placeholder="请输入年龄" variant="outlined" />
                        </div>
                    </div>

                    <!-- 按钮容器 -->
                    <div class="button-container">
                        <var-space :size="[10, 30]">
                            <var-button v-if="selectedRecord.validFlag == 1" type="danger" @click="showConfirm = true">删除此用户</var-button>
                            <var-button v-if="selectedRecord.validFlag == 0" type="success" @click="showRecoverConfirm = true">恢复用户</var-button>
                            <var-button block color="#006263" text-color="white" @click="updatePatientInfo">保存修改</var-button>
                        </var-space>
                    </div>
                </div>
            </var-loading>
        </var-popup>
    </div>
</template>

<script>
import dayjs from 'dayjs';

export default {
    name: 'managerPatient',
    data() {
        return {
            headers:['姓名', '性别', '年龄', '就诊科室', '创建人姓名', '注册时间', '查看就诊记录', '编辑病人信息'],
            sexOptions: [
                { label: '男', value: 'MAN' },
                { label: '女', value: 'WOMAN' }
            ],
            deleteLoading: false, //删除病人信息加载状态
            recoverLoading: false, //恢复病人信息加载状态
            searchValue: '', // 搜索框的值
            loading: false, //个人信息弹窗加载状态
            listLoading: false, //病人列表加载状态
            showCenterPopup: false, //个人信息弹窗
            showConfirm: false, //删除病人信息弹窗
            showRecoverConfirm: false, //恢复病人信息弹窗
            list: [], //页面显示的数据（根据搜索条件过滤）
            currentPage: 1,
            recordList: [], //病人记录列表
            showRecordPopup: false, //病人记录弹窗
            pageSize: 10, //每页显示的数量
            total: 0, //总数据量
            activeTab: 0,
            validFlag: 1,
            selectedRecord: {}, //被选中的病人信息
            updatePatient: {} //用于临时存储修改后的病人信息
        };
    },

    mounted() {
        this.getAllPatient();
    },
    watch: {
        activeTab(newVal, oldVal) {
            if (newVal !== oldVal) {
                this.currentPage = 1;
                this.getAllPatient();
            }
        }
    },
    computed: {
        totalPages() {
            return this.list.length;
        },
        nameRules() {
            return [(v) => !!v || '姓名不能为空', (v) => (v && v.length >= 2) || '姓名至少2个字符'];
        },
        phoneRules() {
            return [(v) => !!v || '手机号不能为空', (v) => /^1[3-9]\d{9}$/.test(v) || '手机号格式错误'];
        },
        ageRules() {
            return [(v) => Number(v) > 0 || '年龄必须大于0', (v) => Number(v) < 120 || '年龄不能超过120'];
        }
    },
    methods: {
        formatDate(date) {
            if (date == null) {
                return '';
            }
            return dayjs(date).format('YYYY年MM月DD日 HH:mm:ss');
        },
        format(date) {
            return dayjs(date).format('YYYY-MM-DD-HH-mm-ss');
        },
        async getRecord(patientId) {
            const res = await this.$api.record.getRecordHistory({ patientId });
            if (res.success) {
                this.recordList = res.data;
                this.showRecordPopup = true;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        // 获取患者记录详情
        async getRecordDetails(recordId) {
        this.$router.push({ name: 'recordDetails', params:{ recordId } });
        },
        // 获取病人列表
        async getAllPatient() {
            this.list = [];
            const typeMap = [1, 0];
            const type = typeMap[this.activeTab];
            this.listLoading = true;
            const res = await this.$api.patient.getAllPatient({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                type: type
            });
            this.listLoading = false;
            if (res.success) {
                this.list = res.data.list;
                this.total = res.data.total || 0;
            } else {
                this.list = [];
                this.total = 0;
                this.$api.notify.error('获取病人列表失败');
            }
        },
        // 删除病人信息
        async deletePatient(action, done) {
            if (action === 'confirm') {
                this.deleteLoading = true;
                const res = await this.$api.patient.updatePatientInfo({
                    departmentId: this.selectedRecord.departmentId,
                    patientId: this.selectedRecord.patientId,
                    validFlag: 0
                });
                this.deleteLoading = false;
                if (res.success) {
                    this.$api.notify.success('病人信息已成功删除');
                    this.showConfirm = false;
                    this.getAllPatient();
                    this.showCenterPopup = false;
                } else {
                    this.$api.notify.error(res.error);
                    this.showConfirm = false;
                    this.showCenterPopup = true;
                }
            }
            done();
        },
        // 恢复病人信息
        async recoverPatient(action, done) {
            if (action === 'confirm') {
                this.recoverLoading = true;
                const res = await this.$api.patient.updatePatientInfo({
                    departmentId: this.selectedRecord.departmentId,
                    patientId: this.selectedRecord.patientId,
                    validFlag: 1
                });
                if (res.success) {
                    this.$api.notify.success('病人信息已成功恢复');
                    this.showRecoverConfirm = false;
                    this.getAllPatient();
                    this.showCenterPopup = false;
                } else {
                    this.$api.notify.error(res.error);
                    this.showRecoverConfirm = false;
                    this.showCenterPopup = true;
                }
            }
            done();
        },
        // 更新病人信息
        async updatePatientInfo(action, done) {
            if (action === 'confirm') return done?.();
            if (!this.validateForm(this.updatePatient)) return done?.();
            const payload = Object.keys(this.updatePatient).reduce((acc, key) => {
                if (this.updatePatient[key] != this.selectedRecord[key]) {
                    acc[key] = this.updatePatient[key];
                }
                return acc;
            }, {});
            //空修改检测
            if (Object.keys(payload).length === 0) {
                this.$api.notify.warning('未做任何修改，请重新输入');
                return done?.();
            }
            //请求配置
            payload.departmentId = this.selectedRecord.departmentId;
            payload.patientId = this.selectedRecord.patientId;
            this.loading = true;
            const res = await this.$api.patient.updatePatientInfo(payload);
            if (res.success) {
                this.list = res.data;
                this.getAllPatient();
                this.$api.notify.success('病人信息更新成功');
            } else {
                this.$api.notify.error(res.error);
            }
            this.loading = false;
            this.showCenterPopup = false;
            if (typeof done === 'function') {
                done();
            }
        },
        //查看记录
        viewRecord(record) {
            this.selectedRecord = { ...record };
            this.updatePatient = record;
            this.showCenterPopup = true;
        },
        //处理分页变化
        handlePageChange(page, pageSize) {
            if (page !== this.currentPage) {
                this.currentPage = page;
                this.getAllPatient();
            }
            if (this.pageSize !== pageSize) {
                this.pageSize = pageSize;
                this.currentPage = 1; // 切换分页大小时重置到第一页
                this.getAllPatient();
            }
        },

        validateForm(record) {
            if (!record.name) {
                this.$api.notify.warning('姓名不能为空');
                return false;
            }
            if (record.name.length < 2) {
                this.$api.notify.warning('姓名至少2个字符');
                return false;
            }
            if (!record.phone) {
                this.$api.notify.warning('手机号不能为空');
                return false;
            }
            if (!/^\d{11}$/.test(record.phone)) {
                this.$api.notify.warning('请输入有效的11位手机号');
                return false;
            }
            if (!record.age) {
                this.$api.notify.warning('年龄不能为空');
                return false;
            }
            if (record.age < 1 || record.age > 120) {
                this.$api.notify.warning('年龄不在有效范围内');
                return false;
            }
            return true;
        }
    }
};
</script>

<style scoped>
.table-example-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 60px;
    padding: 0 16px;
}

.popup-example-block {
    padding: 36px;
    width: 500px;
    height: 650px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.button-container {
    margin-top: auto;
    display: flex;
    justify-content: center;
}
</style>
